package com.demo.handler;

import com.demo.model.AuthConstants;
import com.demo.model.ResultMsg;
import com.demo.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AppLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        // 获取令牌
        String authorizationValue = request.getHeader(AuthConstants.AUTHORIZATION);
        String jwt_token = authorizationValue.replaceFirst(AuthConstants.BEARER, "");
        // 删除 redis 中的token
        redisTemplate.delete(AuthConstants.TOKEN_PREFIX + jwt_token);

        // 响应结果
        ResponseUtil.writeJson(response, ResultMsg.OK("退出成功"));
    }
}
